package com.aurora.leetcode.answer;

import com.aurora.leetcode.util.MyUtils;

/**
 * @author : Aurora
 * @date : 4/1/24 8:44 AM
 * @description 给你一个按 非递减顺序 排序的整数数组 nums，返回 每个数字的平方 组成的新数组，要求也按 非递减顺序 排序。
 */
public class SortedSquares_977 {

    //self解法一：冒泡排序+遍历平方
    public int[] sortedSquaresOne(int[] nums) {
        for(int i=0; i<nums.length; ++i){
            for(int j=0; j<nums.length-1; ++j){
                int firstNum = nums[j]*nums[j];
                int secondNum = nums[j+1]*nums[j+1];
                if(firstNum > secondNum){
                    int temp = nums[j];
                    nums[j] = nums[j+1];
                    nums[j+1] = temp;
                }
            }
        }
        for(int i=0; i<nums.length; ++i){
            nums[i] = nums[i]*nums[i];
        }
        return nums;
    }
    //self解法二：双指针+额外数组
    public int[] sortedSquareTwo(int[] nums){
        int length = nums.length -1 ;
        int left = 0;
        int right = length;
        int[] newArray = new int[nums.length];
        while(left < right){
            int leftNum = nums[left]*nums[left];
            int rightNum = nums[right]*nums[right];
            if(leftNum <= rightNum){
                newArray[length--] = rightNum;
                right--;
            }else{
                newArray[length--] = leftNum;
                left++;
            }
        }
        newArray[length] = nums[left]*nums[left];
        return newArray;
    }


//[-4,-1,0,3,10]
//[-7,-3,2,3,11]
//[-5,-3,-2,-1]
    public static void main(String[] args) {
        MyUtils myUtils = new MyUtils();
        SortedSquares_977 obj = new SortedSquares_977();
        int[] nums1 = new int[]{-4,-1,0,3,10};
//        int[] nums1 = new int[]{-7,-3,2,3,11};
        int[] sortedOne = obj.sortedSquaresOne(nums1);
        myUtils.printArray(sortedOne);
        int[] sortedTwo = obj.sortedSquareTwo(nums1);
        myUtils.printArray(sortedTwo);
    }

}
